<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>帮助中心</h3>
    </div>
    <el-row style="margin-top: 1.5rem; width: 100%">
      <!-- 顶部搜索栏 -->
      <div style="width: 100%">
        <el-form :model="searchForm" ref="searchFormRef" label-width="auto">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="标题" prop="title">
                <el-input v-model="searchForm.title" placeholder="请输入标题" @blur="getData" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-col :xs="24" :sm="12" :lg="20">
          <el-button @click="showDialog('add')" v-ripple>新增帮助</el-button>
        </el-col>
      </div>
      <div> </div>
    </el-row>

    <ArtTable :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <!-- <el-table-column label="图标名称" prop="typename" /> -->
        <el-table-column label="排序" prop="sort" align="center" />
        <el-table-column label="标题" prop="title">
          <template #default="scope" style="width: 500px">
            <div class="bankcont_title">
              <div class="bankcont_title_text">{{ scope.row.title }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column #default="scope" label="状态" align="center">
          <el-switch v-model="scope.row.status" @click="editStatus(scope.row.id, scope.row.status)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="updateTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </ArtTable>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增分组' : '编辑分组'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="内容" prop="remark">
          <ArtWangEditor v-model="editorHtml" class="addcont" />
        </el-form-item>
        <el-form-item label="启动状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import { helpList, addHelpCenter, DelHelpCenter } from '@/api/driverSchoolApi'
import { number } from 'echarts'

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const menuList = computed(() => useMenuStore().getMenuList)
//富文本编辑器
const editorHtml = ref(``)

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '请输入正确排序', trigger: 'blur' }]
})

const form = reactive({
  id: '',
  sort: '1',
  title: '',
  remark: '',
  status: Number('')
})

const tableData = ref([])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    form.id = row.id
    form.sort = row.sort
    editorHtml.value = row.remark
    form.title = row.title
    form.status = row.status == true ? 1 : 0
  } else {
    form.id = ''
    form.sort = '1'
    editorHtml.value = ''
    form.title = ''
    form.status = 1
  }
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true
    const { code, data } = await helpList(filterEmptyValues({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      queryCondition: searchForm.title,
      queryStartTime: searchForm.startTime ? formatDate(searchForm.startTime) : '',
      queryEndTime: searchForm.endTime ? formatDate(searchForm.endTime) : ''
    }))
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}
const refresh = () => {
  getData()
}
const timeChange = (e: any) => {
  console.log(e, 'e====')
  searchForm.startTime = e[0]
  searchForm.endTime = e[1]
  getData()
}

const showPermissionDialog = () => {
  permissionDialog.value = true
}

const defaultProps = {
  children: 'children',
  label: (data: any) => formatMenuTitle(data.meta?.title) || ''
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该分组吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelHelpCenter(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  console.log(1111)

  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      if (dialogType.value === 'add') {
        let res = await addHelpCenter({
          title: form.title,
          sort: form.sort,
          status: form.status,
          remark: editorHtml.value
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        let res = await addHelpCenter({
          id: form.id,
          title: form.title,
          status: form.status,
          sort: form.sort,
          remark: editorHtml.value
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      }
    }
  })
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
//搜索刷新等
const search = () => {
  getData()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // formEl.resetFields()
  searchForm.title = ''
  datavalue1.value = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
}
const searchFormRef = ref<FormInstance>()
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const changeColumn = (list: any) => {
  columns.values = list
}
const searchForm = reactive({
  title: '',
  startTime: '',
  endTime: ''
})
const datavalue1 = ref('') //创建时间：
async function editStatus(id: any, status: number) {
  try {
    const res = await addHelpCenter({
      id,
      status
    })
    if (res.code === '0') {
    }
  } catch (e) {
  } finally {
    await getData()
  }
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tag-item+.tag-item {
  margin-left: 5px;
}

.label {
  float: left;
  margin: 0.5rem 0 0.5rem 1.5rem;
  display: inline;
}

.labellist .label:nth-child(1) {
  margin-left: 0;
}

.bankcont_title_text {
  float: left;
  margin-right: 1rem;
  font-weight: bold;
}

.label_sonli {
  color: #5d87ff;
}

.cell {
  width: 500px;
}

.tag-item {
  margin-left: 5px;
}

.tagcontsize {
  color: #999;
}

.tagcontbigsize {
  margin-top: 0.5rem;
}

.cartcont {
  margin-top: 0.5rem;
}

.tableimg {
  width: 2rem;
  height: 2rem;
}
</style>
